

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=dark>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/my-blog/img/fluid.png">
  <link rel="icon" href="/my-blog/img/fluid.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="木舟">
  <meta name="keywords" content="python Vue Test 测试开发 自动化测试">
  
    <meta name="description" content="前言任何项目中，都避免不了和函数打交道。 不管是用别人写好的函数，还是说自己去封装一个函数，总归来说，程序能够正常的运行，常常会围绕着如何设计好函数而展开。 并且，设计好函数，可以让你少写很多代码。 想必大家都听过程序编写原则：高内聚，低耦合 这个原则，很大程序上是告诉大家，如何设计好函数来进行程序的拼接。 那么，函数到底是什么？ 函数可以理解成是一个特定的功能实现，或者说一个可以将数据进行加工的">
<meta property="og:type" content="article">
<meta property="og:title" content="python函数">
<meta property="og:url" content="https://walker_kwu.gitee.io/my-blog/2023/03/05/python/base/python%E5%87%BD%E6%95%B0/">
<meta property="og:site_name" content="My Blog">
<meta property="og:description" content="前言任何项目中，都避免不了和函数打交道。 不管是用别人写好的函数，还是说自己去封装一个函数，总归来说，程序能够正常的运行，常常会围绕着如何设计好函数而展开。 并且，设计好函数，可以让你少写很多代码。 想必大家都听过程序编写原则：高内聚，低耦合 这个原则，很大程序上是告诉大家，如何设计好函数来进行程序的拼接。 那么，函数到底是什么？ 函数可以理解成是一个特定的功能实现，或者说一个可以将数据进行加工的">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2023-03-05T07:51:21.000Z">
<meta property="article:modified_time" content="2023-05-23T10:37:53.264Z">
<meta property="article:author" content="木舟">
<meta property="article:tag" content="测试开发">
<meta property="article:tag" content="Python基础">
<meta name="twitter:card" content="summary_large_image">
  
  
    <meta name="referrer" content="no-referrer-when-downgrade">
  
  
  <title>python函数 - My Blog</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/my-blog/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/my-blog/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/my-blog/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"walker_kwu.gitee.io","root":"/my-blog/","version":"1.9.2","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"left","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/my-blog/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/my-blog/js/utils.js" ></script>
  <script  src="/my-blog/js/color-schema.js" ></script>
  


  
<meta name="generator" content="Hexo 6.2.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/my-blog/">
      <strong>木舟</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/my-blog/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/my-blog/img/default.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="python函数"></span>
          
        </div>

        
          
  <div class="mt-3">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-author" aria-hidden="true"></i>
        木舟
      </span>
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2023-03-05 15:51" pubdate>
          2023年3月5日 下午
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          8.2k 字
        
      </span>
    

    

    
    
      
        <span id="busuanzi_container_page_pv" style="display: none">
          <i class="iconfont icon-eye" aria-hidden="true"></i>
          <span id="busuanzi_value_page_pv"></span> 次
        </span>
        
      
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="padding-left: 2rem; margin-right: -1rem">
    <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">python函数</h1>
            
              <p class="note note-info">
                
                  
                    本文最后更新于：2023年5月23日 晚上
                  
                
              </p>
            
            
              <div class="markdown-body">
                
                <h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><p>任何项目中，都避免不了和函数打交道。</p>
<p>不管是用别人写好的函数，还是说自己去封装一个函数，总归来说，程序能够正常的运行，常常会围绕着如何设计好函数而展开。</p>
<p>并且，设计好函数，可以让你少写很多代码。</p>
<p>想必大家都听过程序编写原则：高内聚，低耦合</p>
<p>这个原则，很大程序上是告诉大家，如何设计好函数来进行程序的拼接。</p>
<p>那么，函数到底是什么？</p>
<p>函数可以理解成是一个特定的功能实现，或者说一个可以将数据进行加工的工厂，也可以看出一个精密的计算工具。</p>
<p>来点有趣的：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;                            _ooOoo_  &quot;</span>)<br><span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;                           o8888888o  &quot;</span>)<br><span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;                           88  .  88  &quot;</span>)<br><span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;                           (| -_- |)  &quot;</span>)<br><span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;                            O\\ = /O  &quot;</span>)<br><span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;                        ____/`---&#x27;\\____  &quot;</span>)<br><span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;                      .   &#x27; \\| |// `.  &quot;</span>)<br><span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;                       / \\||| : |||// \\  &quot;</span>)<br><span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;                     / _||||| -:- |||||- \\  &quot;</span>)<br><span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;                       | | \\\\\\ - /// | |  &quot;</span>)<br><span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;                     | \\_| &#x27;&#x27;\\---/&#x27;&#x27; | |  &quot;</span>)<br><span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;                      \\ .-\\__ `-` ___/-. /  &quot;</span>)<br><span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;                   ___`. .&#x27; /--.--\\ `. . __  &quot;</span>)<br><span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;                .&quot;</span><span class="hljs-string">&quot; &#x27;&lt; `.___\\_&lt;|&gt;_/___.&#x27; &gt;&#x27;&quot;</span><span class="hljs-string">&quot;.  &quot;</span>)<br><span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;               | | : `- \\`.;`\\ _ /`;.`/ - ` : | |  &quot;</span>)<br><span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;                 \\ \\ `-. \\_ __\\ /__ _/ .-` / /  &quot;</span>)<br><span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;         ======`-.____`-.___\\_____/___.-`____.-&#x27;======  &quot;</span>)<br><span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;                            `=---=&#x27;  &quot;</span>)<br><span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;  &quot;</span>)<br><span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;         .............................................  &quot;</span>)<br><span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;                  佛祖镇楼                  BUG辟易  &quot;</span>)<br><span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;          佛曰:  &quot;</span>)<br><span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;                  写字楼里写字间，写字间里程序员；  &quot;</span>)<br><span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;                  程序人员写程序，又拿程序换酒钱。  &quot;</span>)<br><span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;                  酒醒只在网上坐，酒醉还来网下眠；  &quot;</span>)<br><span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;                  酒醉酒醒日复日，网上网下年复年。  &quot;</span>)<br><span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;                  但愿老死电脑间，不愿鞠躬老板前；  &quot;</span>)<br><span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;                  奔驰宝马贵者趣，公交自行程序员。  &quot;</span>)<br><span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;                  别人笑我忒疯癫，我笑自己命太贱；  &quot;</span>)<br><span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;                  不见满街漂亮妹，哪个归得程序员？&quot;</span>)<br></code></pre></td></tr></table></figure>

<p>上述代码运行后，可以生成一个佛祖，开玩笑的说：把这个放开项目运行主文件中，可以起到“辟邪”的作用。</p>
<p>那么，如果这一段代码我想要在很多文件中都植入，那是不是意味着我需要复制粘贴很多次，并且它会占用很大的文件空间。</p>
<p>那么，我们可以把这段代码封装成一个函数，需要用到的时候，只需要简单的调用它即可。</p>
<h1 id="函数定义与调用"><a href="#函数定义与调用" class="headerlink" title="函数定义与调用"></a>函数定义与调用</h1><h2 id="定义"><a href="#定义" class="headerlink" title="定义"></a>定义</h2><p>函数的定义需要用到关键字 <code>def</code></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">def</span> <span class="hljs-title function_">函数名</span>():<br>    <span class="hljs-comment"># your code</span><br>    ...<br></code></pre></td></tr></table></figure>

<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">def</span> <span class="hljs-title function_">test</span>():<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;我是test函数&quot;</span>)<br></code></pre></td></tr></table></figure>

<h2 id="调用"><a href="#调用" class="headerlink" title="调用"></a>调用</h2><p>函数的调用格式为 <code>函数名()</code></p>
<p>函数名加上括号即可运行，和我们之前用到的是一样的。</p>
<p>加上括号是强制要求，因为括号里可以传递参数</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">def</span> <span class="hljs-title function_">test</span>():<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;我是test函数&quot;</span>)<br><br>test()<br><br><span class="hljs-comment"># 结果：我是test函数</span><br></code></pre></td></tr></table></figure>

<h1 id="函数说明"><a href="#函数说明" class="headerlink" title="函数说明"></a>函数说明</h1><p>函数说明可以理解为是 <strong>给函数加上注释</strong></p>
<p>但由于函数以及我们后面学习的 <strong>类</strong> 都是比较复杂的逻辑，所以和一般的注释不同</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">def</span> <span class="hljs-title function_">test</span>():<br>    <span class="hljs-string">&quot;&quot;&quot;</span><br><span class="hljs-string">    这里写上函数的说明</span><br><span class="hljs-string">    &quot;&quot;&quot;</span><br>    ...<br></code></pre></td></tr></table></figure>

<h1 id="函数参数"><a href="#函数参数" class="headerlink" title="函数参数"></a>函数参数</h1><p>函数参数可以说是伟大的发明，因为它让函数有了生命</p>
<p>一个函数的功能，会被传递的参数所影响，让其变得富有生命。</p>
<p>我们试想一下，我们现在要实现一个 <strong>两数相加</strong> 的函数</p>
<p>如果没有函数参数，我们也许说写成这个样子</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">def</span> <span class="hljs-title function_">add</span>():<br>    x = <span class="hljs-number">1</span><br>    y = <span class="hljs-number">2</span><br>    <span class="hljs-built_in">print</span>(x + y)<br></code></pre></td></tr></table></figure>

<p>但是这样的函数对于我们来说有什么卵用？难不成我每次调用的时候还得去手动修改x和y吗</p>
<p>而且也不能多个地方调用，所以说这个函数存在很大的问题 <strong>没有生命</strong></p>
<p>接下来我们来认识一下 <strong>具备参数的函数</strong> 如何编写</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">def</span> <span class="hljs-title function_">add</span>(<span class="hljs-params">x, y</span>):<br>    <span class="hljs-built_in">print</span>(x + y)<br><br>add(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>)<br>add(<span class="hljs-number">3</span>, <span class="hljs-number">4</span>)<br></code></pre></td></tr></table></figure>

<p>定义/传递多个参数时，参数之间需要有逗号隔开</p>
<h2 id="形参与实参"><a href="#形参与实参" class="headerlink" title="形参与实参"></a>形参与实参</h2><p>形参和实参是一个名词，指代着不同的意思。</p>
<p>我们定义函数的参数时，叫做形参</p>
<p>我们调用函数传递的参数，叫做实参。</p>
<p>实参顾名思义，就是函数运行时实际的参数值</p>
<p>形参顾名思义，就是函数运行时定义的形式上的参数</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">def</span> <span class="hljs-title function_">add</span>(<span class="hljs-params">x, y</span>):  <span class="hljs-comment"># x y 就是形参</span><br>    <span class="hljs-built_in">print</span>(x + y)<br><br>add(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>)  <span class="hljs-comment"># 1 2 为实参</span><br>add(<span class="hljs-number">3</span>, <span class="hljs-number">4</span>)  <span class="hljs-comment"># 3 4 为实参</span><br></code></pre></td></tr></table></figure>

<h2 id="函数类型"><a href="#函数类型" class="headerlink" title="函数类型"></a>函数类型</h2><p>函数的传递方式的不同，我们用函数类型来进行区分</p>
<h3 id="位置参数"><a href="#位置参数" class="headerlink" title="位置参数"></a>位置参数</h3><p>顾名思义，就是按照顺序传入的参数</p>
<p>函数运行时，按照顺序进行取值。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">def</span> <span class="hljs-title function_">add</span>(<span class="hljs-params">x, y</span>):<br>    <span class="hljs-built_in">print</span>(x + y)<br><br>add(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>)<br>add(<span class="hljs-number">3</span>, <span class="hljs-number">4</span>)<br></code></pre></td></tr></table></figure>

<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-comment">#就业榜单输出学员详细信息： 姓名  工作年限  城市  学前薪资  学后薪资</span><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">offerinfo</span>(<span class="hljs-params">name,work_age,work_city,pre_gz,bf_gz</span>):<br>    <span class="hljs-built_in">print</span>(<br>        <span class="hljs-string">f&quot;调用函数：offerinfo 姓名 :<span class="hljs-subst">&#123;name&#125;</span> ,工作年限:<span class="hljs-subst">&#123;work_age&#125;</span> , 所在城市:<span class="hljs-subst">&#123;work_city&#125;</span>， 学前薪资: <span class="hljs-subst">&#123;pre_gz&#125;</span>k 学后薪资:<span class="hljs-subst">&#123;bf_gz&#125;</span>k ，涨薪<span class="hljs-subst">&#123;bf_gz-pre_gz&#125;</span>k&quot;</span>)<br><span class="hljs-comment"># 必需参数(参数顺序、参数个数、参数类型都必须跟函数定义一致)</span><br>offerinfo(<span class="hljs-string">&#x27;alone&#x27;</span>,<span class="hljs-number">2</span>,<span class="hljs-string">&#x27;深圳&#x27;</span>,<span class="hljs-number">15</span>,<span class="hljs-number">20</span>)<br><br></code></pre></td></tr></table></figure>

<p>上述代码，add运行时，根据顺序来定义x和y的值。</p>
<p>位置参数为 <strong>必须参数</strong>，并且数量是定死的，多一个少一个都不行。</p>
<h2 id="关键字参数"><a href="#关键字参数" class="headerlink" title="关键字参数"></a>关键字参数</h2><p>关键字参数为 <strong>指定参数</strong></p>
<p>意思为，指定某个参数运行时为某个值，避免了参数传递错误的风险。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-comment">#就业榜单输出学员详细信息： 姓名  工作年限  城市  学前薪资  学后薪资</span><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">offerinfo</span>(<span class="hljs-params">name,work_age,work_city,pre_gz,bf_gz</span>):<br>    <span class="hljs-built_in">print</span>(<br>        <span class="hljs-string">f&quot;调用函数：offerinfo 姓名 :<span class="hljs-subst">&#123;name&#125;</span> ,工作年限:<span class="hljs-subst">&#123;work_age&#125;</span> , 所在城市:<span class="hljs-subst">&#123;work_city&#125;</span>， 学前薪资: <span class="hljs-subst">&#123;pre_gz&#125;</span>k 学后薪资:<span class="hljs-subst">&#123;bf_gz&#125;</span>k ，涨薪<span class="hljs-subst">&#123;bf_gz-pre_gz&#125;</span>k&quot;</span>)<br><span class="hljs-comment"># 关键字参数</span><br>offerinfo(work_age=<span class="hljs-number">2</span>,name=<span class="hljs-string">&#x27;alone&#x27;</span>,work_city=<span class="hljs-string">&#x27;深圳&#x27;</span>,bf_gz=<span class="hljs-number">20</span>,pre_gz=<span class="hljs-number">15</span>)<br></code></pre></td></tr></table></figure>

<h2 id="默认参数"><a href="#默认参数" class="headerlink" title="默认参数"></a>默认参数</h2><p>默认参数，顾名思义，就是给参数一个默认值。</p>
<p>所以一个参数为默认参数，则 <strong>如果传递了实参，则以传递的为准，如果没有传递，则以默认值为准</strong></p>
<p>所以默认参数有几个很大的作用：</p>
<ul>
<li>为函数增加功能，不影响旧模块的使用</li>
<li>为控制函数运行走向</li>
</ul>
<p>默认参数定义时，需要写在最后面，可以定义多个</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">def</span> <span class="hljs-title function_">add</span>(<span class="hljs-params">x, y, z=<span class="hljs-number">0</span></span>):<br>    <span class="hljs-keyword">if</span> z:<br>        <span class="hljs-built_in">print</span>(x + y + z)<br>    <span class="hljs-keyword">else</span>:<br>        <span class="hljs-built_in">print</span>(x + y)<br><br>add(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>)<br>add(<span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>)<br></code></pre></td></tr></table></figure>

<p>上述函数，原本的功能为 <strong>两数相加</strong></p>
<p>如今加上了 <strong>默认参数z</strong>, 定义初始值为0。<strong>既不影响原来调用的功能，也可以增加新的功能</strong></p>
<h2 id="不定参数"><a href="#不定参数" class="headerlink" title="不定参数"></a>不定参数</h2><p>不定参数也可以叫做 <strong>万能参数</strong></p>
<p>意思是，顺便你传递多少个都可以。</p>
<p>当然，函数能不能处理是编写者需要考虑的事情。</p>
<p>不定参数也会和后面的 <strong>装饰器</strong> 关联，后面会做介绍。</p>
<h3 id=""><a href="#" class="headerlink" title="*"></a>*</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">def</span> <span class="hljs-title function_">add</span>(<span class="hljs-params">x, y, *args</span>):<br>    <span class="hljs-built_in">sum</span> = x + y<br><br>    <span class="hljs-keyword">for</span> arg <span class="hljs-keyword">in</span> args:<br>        <span class="hljs-built_in">sum</span> += arg<br><br>    <span class="hljs-built_in">print</span>(<span class="hljs-built_in">sum</span>)<br><br>add(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>)<br>add(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>)<br></code></pre></td></tr></table></figure>

<p><code>*args</code> 中，<code>args</code>只是参数名，可以叫其他名字都可以</p>
<p>重要的是 <code>*</code>，这个符号可以将多余的参数 <strong>塞入</strong> 定义的参数名中</p>
<p>比如上述代码中 <code>4, 5, 6, 7, 8</code> 即为多余的参数，我们可以将它全部的塞入 <code>args</code>中</p>
<p>所以，想要容纳 <strong>不定数量</strong> 的参数，<code>args</code>最终的形态肯定是一个容器，python将其规定为 <strong>元组</strong> 类型</p>
<p>也是因为 <strong>元组的值不可变</strong></p>
<h3 id="-1"><a href="#-1" class="headerlink" title="**"></a>**</h3><p>上述介绍的是 <strong>不定参数中的位置参数</strong></p>
<p>下面介绍的是 <strong>不定参数中的位置参数</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">def</span> <span class="hljs-title function_">userInfo</span>(<span class="hljs-params">username, age, **kwargs</span>):<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;我叫 <span class="hljs-subst">&#123;username&#125;</span>, 今年 <span class="hljs-subst">&#123;age&#125;</span>&quot;</span>)<br>    <span class="hljs-keyword">if</span> kwargs:<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;对了我还有其他的信息可以告诉你&quot;</span>)<br>        <span class="hljs-keyword">for</span> key, value <span class="hljs-keyword">in</span> kwargs.items():<br>            <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;我的 <span class="hljs-subst">&#123;key&#125;</span> 为 <span class="hljs-subst">&#123;value&#125;</span>&quot;</span>)<br><br>userInfo(<span class="hljs-string">&#x27;muzhou&#x27;</span>, <span class="hljs-string">&#x27;18&#x27;</span>)<br>userInfo(<span class="hljs-string">&#x27;muzhou&#x27;</span>, <span class="hljs-string">&#x27;18&#x27;</span>, sex=<span class="hljs-string">&#x27;man&#x27;</span>, city=<span class="hljs-string">&#x27;成都&#x27;</span>)<br></code></pre></td></tr></table></figure>

<p>同样，<code>kwargs</code> 也只是个名字, 可以叫其他的</p>
<p>前面有两个 <code>*</code> 则为 <strong>不定参数中的位置参数</strong></p>
<p>最终的形态为 <strong>字典</strong></p>
<p>因为只有 <strong>字典</strong> 是 <strong>key-value</strong> 结构, 能够很好的存取关键字参数</p>
<p>但因为字典的特性, kwargs的值是可以被修改的, 使用时需要注意.</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">def</span> <span class="hljs-title function_">userInfo</span>(<span class="hljs-params">username, age, **kwargs</span>):<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;我叫 <span class="hljs-subst">&#123;username&#125;</span>, 今年 <span class="hljs-subst">&#123;age&#125;</span>&quot;</span>)<br>    kwargs[<span class="hljs-string">&#x27;city&#x27;</span>] = <span class="hljs-string">&#x27;xx&#x27;</span><br>    kwargs[<span class="hljs-string">&#x27;city1&#x27;</span>] = <span class="hljs-string">&#x27;xx&#x27;</span><br>    <span class="hljs-keyword">if</span> kwargs:<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;对了我还有其他的信息可以告诉你&quot;</span>)<br>        <span class="hljs-keyword">for</span> key, value <span class="hljs-keyword">in</span> kwargs.items():<br>            <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;我的 <span class="hljs-subst">&#123;key&#125;</span> 为 <span class="hljs-subst">&#123;value&#125;</span>&quot;</span>)<br><br>userInfo(<span class="hljs-string">&#x27;muzhou&#x27;</span>, <span class="hljs-string">&#x27;18&#x27;</span>)<br>userInfo(<span class="hljs-string">&#x27;muzhou&#x27;</span>, <span class="hljs-string">&#x27;18&#x27;</span>, sex=<span class="hljs-string">&#x27;man&#x27;</span>, city=<span class="hljs-string">&#x27;成都&#x27;</span>)<br></code></pre></td></tr></table></figure>

<p>为什么叫他们为 <strong>万能参数</strong>?</p>
<p>因为当这两种参数同时定义时, 你可以以任何形式/数量的传递参数</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">def</span> <span class="hljs-title function_">test</span>(<span class="hljs-params">*args, **kwargs</span>):<br>    <span class="hljs-built_in">print</span>(args)<br>    <span class="hljs-built_in">print</span>(kwargs)<br><br>test(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, a=<span class="hljs-number">3</span>, b=<span class="hljs-number">4</span>)<br></code></pre></td></tr></table></figure>

<h1 id="函数返回值"><a href="#函数返回值" class="headerlink" title="函数返回值"></a>函数返回值</h1><p>函数可以有用返回值, 具备返回值的函数, 还能叫做一个工具/工厂</p>
<p>因为它可以进行数据加工后再给你返回出来.</p>
<p>返回值可以通过 <code>return</code> 来进行返回</p>
<p><code>return</code>后面可以跟着一个 <strong>表达式</strong>, 即可以为: 一个变量/值/计算公式/函数</p>
<h2 id="基本写法"><a href="#基本写法" class="headerlink" title="基本写法"></a>基本写法</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">def</span> <span class="hljs-title function_">add</span>(<span class="hljs-params">x, y</span>):<br>    <span class="hljs-keyword">return</span> x + y<br><br>sum1 = add(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>)<br><span class="hljs-built_in">print</span>(sum1)<br><span class="hljs-built_in">print</span>(add(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>))<br><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">reduce</span>(<span class="hljs-params">x, y</span>):<br>    p = x - y<br>    <span class="hljs-keyword">return</span> p<br><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">test</span>():<br>    <span class="hljs-keyword">return</span> add(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>)<br><br><span class="hljs-built_in">print</span>(test())<br></code></pre></td></tr></table></figure>

<h2 id="return可以停止函数"><a href="#return可以停止函数" class="headerlink" title="return可以停止函数"></a>return可以停止函数</h2><p>不论如何, 记住是 <strong>不论如何</strong> 只要触发了 <code>return</code> 函数都会直接停止, <code>return</code>以下的代码都不会被执行</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">def</span> <span class="hljs-title function_">add</span>(<span class="hljs-params">x, y</span>):<br>    <span class="hljs-keyword">return</span> x + y<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;我呆在底下偷偷执行, 嘿嘿嘿&quot;</span>)   <span class="hljs-comment"># 不会被执行</span><br>    <span class="hljs-keyword">return</span> x  <span class="hljs-comment"># 不会被执行</span><br></code></pre></td></tr></table></figure>

<h2 id="返回多个值"><a href="#返回多个值" class="headerlink" title="返回多个值"></a>返回多个值</h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">def</span> <span class="hljs-title function_">test</span>():<br>    <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>, <span class="hljs-number">2</span> ,<span class="hljs-number">3</span><br><br><span class="hljs-built_in">print</span>(test())  <span class="hljs-comment"># (1, 2, 3)</span><br>a, b, c = test()<br><br>a, b = test()  <span class="hljs-comment"># 报错</span><br></code></pre></td></tr></table></figure>

<p>返回多个值时, 值之间需要用逗号隔开</p>
<p>这个时候函数返回出来的值实际上是一个 <strong>元素</strong></p>
<p>所以我们可以使用之前用过的 <strong>解包</strong> 来依次取值</p>
<p>值得注意的是, 一旦使用 <strong>解包</strong>, 那么承接的变量数 <strong>必须一致</strong></p>
<h1 id="匿名函数"><a href="#匿名函数" class="headerlink" title="匿名函数"></a>匿名函数</h1><ul>
<li>此函数不是没有名字，他是有名字的，他的名字就是你给其设置的变量，比如res.</li>
<li>lambda 是定义匿名函数的关键字，相当于函数的def.</li>
<li>lambda 后面直接加形参，形参加多少都可以，只要用逗号隔开就行。</li>
<li>返回值在冒号之后设置，返回值和正常的函数一样,可以是任意数据类型。</li>
<li>匿名函数不管多复杂.只能写一行.且逻辑结束后直接返回数据</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-comment"># 匿名函数,一般用于另一个函数的参数</span><br>res = <span class="hljs-keyword">lambda</span> a, b: a + b<br><span class="hljs-built_in">print</span>(res(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>))<br></code></pre></td></tr></table></figure>

<p>目前匿名函数一般会和高阶函数使用, 如: map/filter/reduce/sorted</p>
<h1 id="打断一下"><a href="#打断一下" class="headerlink" title="打断一下"></a>打断一下</h1><p>如果说上面的内容, 只是让你入门函数的使用</p>
<p>那么后面的 <strong>闭包函数/装饰器/递归函数</strong> </p>
<p>这几个就是函数的高阶用法, 对于初学者来说, 只是简单了解即可.</p>
<p>随着编程经验的增加, 当有需要的时候, 再回过头来深入学习这部分, 会事半功倍</p>
<h1 id="递归函数"><a href="#递归函数" class="headerlink" title="递归函数"></a>递归函数</h1><p>递归函数, 简单来说就是<strong>在函数运行的过程中调用本身</strong></p>
<p>使用递归函数,需要明确两点:</p>
<ul>
<li>要有结束条件</li>
<li>合理的递归条件</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-comment"># 基于递归函数实现，计算阶乘 1*2*3*....*n</span><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">count_2</span>(<span class="hljs-params">n</span>):<br>    <span class="hljs-keyword">if</span> n==<span class="hljs-number">1</span>:<br>        <span class="hljs-keyword">return</span> <span class="hljs-number">1</span><br>    <span class="hljs-keyword">return</span> n*count_2(n-<span class="hljs-number">1</span>)<br>value=count_2(<span class="hljs-number">5</span>)<br><span class="hljs-built_in">print</span>(value)<br></code></pre></td></tr></table></figure>

<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><code class="hljs python">lst = [<br>    <span class="hljs-number">1</span>, [<br>        <span class="hljs-number">2</span>, [<br>            <span class="hljs-number">3</span>, [<br>                <span class="hljs-number">4</span>, [<span class="hljs-number">5</span>]<br>            ]<br>        ]<br>    ]<br>]<br><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">getValue</span>(<span class="hljs-params">dataMap, newLst</span>):<br>    <span class="hljs-keyword">for</span> el <span class="hljs-keyword">in</span> dataMap:<br>        <span class="hljs-keyword">if</span> <span class="hljs-built_in">isinstance</span>(el, <span class="hljs-built_in">list</span>):<br>            getValue(el, newLst)<br>        <span class="hljs-keyword">else</span>:<br>            newLst.append(el)<br><br>newLst = []<br>getValue(lst, newLst)<br><span class="hljs-built_in">print</span>(newLst)<br></code></pre></td></tr></table></figure>

<p>上述代码的作用是: 不管一个数组嵌套的多深, 都能够将其 <strong>扁平化</strong>, 取值到一个新的数组中</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">def</span> <span class="hljs-title function_">test</span>(<span class="hljs-params">n</span>):<br>    <span class="hljs-built_in">print</span>(n)<br>    <span class="hljs-keyword">if</span> n == <span class="hljs-number">1</span>:<br>        <span class="hljs-keyword">return</span> n<br>    <span class="hljs-keyword">else</span>:<br>        test(n - <span class="hljs-number">1</span>)<br>    <span class="hljs-built_in">print</span>(n)<br>test(<span class="hljs-number">10</span>)<br></code></pre></td></tr></table></figure>

<p>以上的代码会输出 <strong>从10输出到1,再从1输出到10</strong></p>
<h1 id="闭包函数"><a href="#闭包函数" class="headerlink" title="闭包函数"></a>闭包函数</h1><p>1、什么是闭包函数<br>一个函数的返回值是另外一个函数，返回的函数调用父函数内部的其他变量，<br>如果返回的函数在外部被执行，就产生了闭包</p>
<p>2、闭包函数的意义及作用<br>作用：使函数外部能够调用函数内部定义的变量</p>
<p>3、闭包函数优缺点：<br>优点：内部函数和局部变量都可以在外部使用<br>缺点：闭包操作导致整个函数的内部环境，被长久保存，占用大量的内存</p>
<p>上面的介绍太过于笼统, 从我的理解角度来说, 闭包最大的作用就是: <strong>保证变量不被环境污染</strong></p>
<p>但也因为这个特点, 导致闭包会造成 <strong>内存泄漏</strong>, 这个就要和python的内存管理机制有关了,这里就不展开赘述了.</p>
<p>比如说我们下面来实现一个计数器</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">def</span> <span class="hljs-title function_">counter</span>(<span class="hljs-params">num</span>):<br>    <span class="hljs-keyword">return</span> num + <span class="hljs-number">1</span><br><br>a = <span class="hljs-number">1</span><br>a = counter(a)<br><span class="hljs-built_in">print</span>(a)<br></code></pre></td></tr></table></figure>

<p>咋一看, 这段程序并没有问题, 但是我现在想要保证 <code>变量a</code> 只能被 <code>counter</code>函数所改变</p>
<p>如果我们没有学习闭包, 是不是这个想法就没法实现?</p>
<p>因为不仅 <code>counter</code>函数可以改变a, 程序的任何一个地方都可以.</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">def</span> <span class="hljs-title function_">counter</span>(<span class="hljs-params">num</span>):<br>    newNum = num<br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">func</span>():<br>        <span class="hljs-keyword">nonlocal</span> newNum<br>        newNum += <span class="hljs-number">1</span><br>        <span class="hljs-keyword">return</span> newNum<br>    <span class="hljs-keyword">return</span> func<br><br>func = counter(<span class="hljs-number">1</span>)<br>a = func()<br><span class="hljs-built_in">print</span>(a)<br>a = func()<br><span class="hljs-built_in">print</span>(a)<br></code></pre></td></tr></table></figure>

<p>这样一来, 比如说我们可以用这个函数来计算某个函数运行的次数</p>
<p>而且这个次数, 不会被其他地方所改变.</p>
<p>每次调用这个函数, 获取到的都是正确的叠加后的次数.</p>
<h1 id="装饰器"><a href="#装饰器" class="headerlink" title="装饰器"></a>装饰器</h1><p>装饰器是python的一大特性, 我们通常借助装饰器来完成对函数的 <strong>前置校验/增补功能</strong></p>
<p>比如:</p>
<ul>
<li>校验权限</li>
<li>打印信息</li>
<li>计算耗时</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br></pre></td><td class="code"><pre><code class="hljs python"><span class="hljs-keyword">import</span> time<br><span class="hljs-comment"># 装饰器不带参数</span><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">runTime</span>(<span class="hljs-params">func</span>):<br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">wrapper</span>(<span class="hljs-params">*args,**kwargs</span>):<br>        start_time = time.time()<br>        <span class="hljs-comment">#执行原来函数的功能</span><br>        func(*args,**kwargs)<br>        <span class="hljs-comment">#执行扩展功能</span><br>        time.sleep(<span class="hljs-number">1</span>)<br>        end_time = time.time()<br>        const = end_time - start_time<br>        <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;统计<span class="hljs-subst">&#123;func.__name__&#125;</span>函数运行耗时<span class="hljs-subst">&#123;const&#125;</span>秒&quot;</span>)<br>    <span class="hljs-keyword">return</span> wrapper<br><br><br><span class="hljs-meta">@runTime    </span><span class="hljs-comment"># 第一件事调用cal_time,第二件事把被装饰的函数名传给cal_time的形参fn</span><br><span class="hljs-keyword">def</span>  <span class="hljs-title function_">welcome_vip</span>():<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;欢迎来到VIP课堂&quot;</span>)<br><span class="hljs-comment">#不加装饰器</span><br>welcome_vip=runTime(welcome_vip)     <span class="hljs-comment">#等同@runTime</span><br>welcome_vip()<br><span class="hljs-comment">#加装饰器,当再次调用welcome_vip的时候，这时的welcome_vip已经不是welcome_vip函数了，是runTime返回wrapper内部函数的地址</span><br>welcome_vip()   <span class="hljs-comment"># 等同于welcome_vip = runTime(welcome_vip)</span><br><span class="hljs-comment"># 装饰器带参数:实质外面再包裹一个函数,最外层接收装饰器传入的参数，第二层接收传入被装饰的函数，第三层给被装饰函数传参进行逻辑判断</span><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">demo</span>(<span class="hljs-params">name</span>):<br>    <span class="hljs-keyword">def</span> <span class="hljs-title function_">runTime</span>(<span class="hljs-params">func</span>):<br>        <span class="hljs-keyword">def</span> <span class="hljs-title function_">wrapper</span>(<span class="hljs-params">*args,**kwargs</span>):<br>            start_time = time.time()<br>            <span class="hljs-comment">#执行原来函数的功能</span><br>            func(*args,**kwargs)<br>            <span class="hljs-comment">#执行扩展功能</span><br>            time.sleep(<span class="hljs-number">1</span>)<br>            end_time = time.time()<br>            const = end_time - start_time<br>            <span class="hljs-built_in">print</span>(<span class="hljs-string">f&quot;统计<span class="hljs-subst">&#123;func.__name__&#125;</span>函数运行耗时<span class="hljs-subst">&#123;const&#125;</span>秒&quot;</span>)<br>        <span class="hljs-keyword">return</span> wrapper<br>    <span class="hljs-keyword">return</span> runTime<br><span class="hljs-meta">@demo(<span class="hljs-params"><span class="hljs-string">&#x27;xingyao&#x27;</span></span>)</span><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">test</span>():<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">&quot;执行test函数&quot;</span>)<br>test()<br><span class="hljs-meta">@cal_time  </span><span class="hljs-comment"># 多层装饰器，先调用最近的</span><br><span class="hljs-meta">@pay_time</span><br><span class="hljs-keyword">def</span> <span class="hljs-title function_">pay_game</span>(<span class="hljs-params">name, game</span>):<br>    <span class="hljs-built_in">print</span>(<span class="hljs-string">&#x27;&#123;&#125;正在玩&#123;&#125;&#x27;</span>.<span class="hljs-built_in">format</span>(name, game))<br></code></pre></td></tr></table></figure>
                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/my-blog/categories/python/" class="category-chain-item">python</a>
  
  
    <span>></span>
    
  <a href="/my-blog/categories/python/Python%E5%9F%BA%E7%A1%80/" class="category-chain-item">Python基础</a>
  
  

  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/my-blog/tags/%E6%B5%8B%E8%AF%95%E5%BC%80%E5%8F%91/">#测试开发</a>
      
        <a href="/my-blog/tags/Python%E5%9F%BA%E7%A1%80/">#Python基础</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>python函数</div>
      <div>https://walker_kwu.gitee.io/my-blog/2023/03/05/python/base/python函数/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>木舟</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2023年3月5日</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>更新于</div>
          <div>2023年5月23日</div>
        </div>
      
      <div class="license-meta-item">
        <div>许可协议</div>
        <div>
          
            
            
              <a target="_blank" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">
              <span class="hint--top hint--rounded" aria-label="BY - 署名">
                <i class="iconfont icon-by"></i>
              </span>
              </a>
            
              <a target="_blank" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">
              <span class="hint--top hint--rounded" aria-label="NC - 非商业性使用">
                <i class="iconfont icon-nc"></i>
              </span>
              </a>
            
              <a target="_blank" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">
              <span class="hint--top hint--rounded" aria-label="SA - 相同方式共享">
                <i class="iconfont icon-sa"></i>
              </span>
              </a>
            
          
        </div>
      </div>
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/my-blog/2023/03/11/python/base/python%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1%EF%BC%88%E4%B8%8A%EF%BC%89/" title="python面向对象（上）">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">python面向对象（上）</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/my-blog/2023/03/04/python/base/python%E5%88%A4%E6%96%AD%E4%B8%8E%E5%BE%AA%E7%8E%AF/" title="python判断与循环">
                        <span class="hidden-mobile">python判断与循环</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <span>By 木舟</span> <i class="iconfont icon-love"></i> 
    </div>
  
  
    <div class="statistics">
  
  

  
    
      <span id="busuanzi_container_site_pv" style="display: none">
        总访问量 
        <span id="busuanzi_value_site_pv"></span>
         次
      </span>
    
    
      <span id="busuanzi_container_site_uv" style="display: none">
        总访客数 
        <span id="busuanzi_value_site_uv"></span>
         人
      </span>
    
    
  
</div>

  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/my-blog/js/events.js" ></script>
<script  src="/my-blog/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/my-blog/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      headingSelector : CONFIG.toc.headingSelector || 'h1,h2,h3,h4,h5,h6',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      collapseDepth   : CONFIG.toc.collapseDepth || 0,
      scrollSmooth    : true,
      headingsOffset  : -boardTop
    });
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.10/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/my-blog/js/local-search.js" ></script>

  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/my-blog/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
